<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" class="m-r-8" :model="queryParams" :inline="true">
        <el-form-item class="input-box">
          <div class="input-group">
            <!-- 题库名称搜索框 -->
            <el-input
              v-model="queryParams.bankKeywords"
              placeholder="题库名称"
              clearable
              class="m-r-8"
              @keyup.enter="handleQuery"
            />
            <!-- 分类选择框 -->
            <el-select
              v-model="queryParams.categoryId"
              placeholder="请选择分类"
              clearable
              filterable
              class="m-r-8"
              @change="handleQuery"
            >
              <el-option
                v-for="category in categoryOptions"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <!-- 还原新增题库按钮到此处 -->
          <el-button type="success" icon="Plus" @click="handleOpenDialog()">新增题库</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="currentPageData" highlight-current-row row-key="id">
        <el-table-column label="序号" align="center" width="80">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="题库名称" align="center">
          <template #default="scope">
            {{ scope.row.title }}
          </template>
        </el-table-column>

        <el-table-column label="分类" align="center">
          <template #default="scope">
            {{
              categoryOptions.find((cat) => cat.id === scope.row.categoryId)?.name ||
              scope.row.categoryName
            }}
          </template>
        </el-table-column>
        <el-table-column label="题目数量" align="center" prop="orderNum" />
        <el-table-column label="上架时间" align="center" prop="creationTime" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.state === 1" type="success">已上架</el-tag>
            <el-tag v-else type="info">已下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="default"
              icon="Edit"
              @click.stop="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              link
              size="default"
              icon="View"
              @click.stop="handleView(scope.row)"
            >
              查看题目
            </el-button>
            <el-button
              :type="scope.row.state === 1 ? 'danger' : 'warning'"
              link
              size="default"
              :icon="scope.row.state === 1 ? 'Bottom' : 'Top'"
              @click.stop="handleStatusChange(scope.row)"
            >
              {{ scope.row.state === 1 ? "下架" : "上架" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination p-8">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 题库详情弹窗 -->
    <el-dialog
      v-model="bankDetailDialog.visible"
      class="bankDetailDialog"
      :title="bankDetailDialog.title"
    >
      <!-- 操作按钮组（仅保留新增题目按钮） -->
      <div style="margin-bottom: 16px; text-align: right">
        <el-button type="success" icon="Plus" @click="handleOpenQuestionDialogWithBank()">
          新增题目
        </el-button>
      </div>

      <el-table
        v-loading="questionLoading"
        style="width: 100%"
        :data="questionList"
        highlight-current-row
        row-key="id"
      >
        <el-table-column label="序号" align="center" width="120">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column width="180" label="题目" align="center" show-overflow-tooltip>
          <template #default="scope">
            {{ scope.row.topic }}
          </template>
        </el-table-column>

        <el-table-column show-overflow-tooltip label="答案" align="center" prop="answer" />

        <el-table-column label="上架时间" align="center" prop="creationTime" />
        <el-table-column label="状态" align="center" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.state === 1" type="success">已上架</el-tag>
            <el-tag v-else type="info">已下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="default"
              icon="Edit"
              @click.stop="handleEditQuestion(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              :type="scope.row.state === 1 ? 'danger' : 'warning'"
              link
              size="default"
              :icon="scope.row.state === 1 ? 'Bottom' : 'Top'"
              @click.stop="handleQuestionStatusChange(scope.row)"
            >
              {{ scope.row.state === 1 ? "下架" : "上架" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 题库表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="450px" @close="resetForm">
      <el-form ref="menuFormRef" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item label="题库" prop="name">
          <el-input v-model="formData.name" placeholder="请输入题库名称" />
        </el-form-item>

        <el-form-item label="题库分类" prop="categoryId">
          <el-select
            v-model="formData.categoryId"
            placeholder="请选择题库分类"
            clearable
            filterable
          >
            <el-option
              v-for="category in categoryOptions"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="是否启用" prop="state">
          <el-switch v-model="formData.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>

    <!-- 题目表单弹窗 -->
    <el-dialog
      v-model="questionDialog.visible"
      style="padding-right: 64px"
      :title="questionDialog.title"
      width="650px"
    >
      <el-form
        ref="questionFormRef"
        :model="questionFormData"
        :rules="questionFormRules"
        label-width="120px"
      >
        <el-form-item label="所属题库" prop="bankID">
          <el-select
            v-model="questionFormData.bankID"
            placeholder="请选择题库名称"
            clearable
            filterable
          >
            <el-option
              v-for="bank in bankList"
              :key="bank.id"
              :label="bank.title"
              :value="bank.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="题目内容" prop="topic">
          <el-input
            v-model="questionFormData.topic"
            type="textarea"
            :rows="2"
            placeholder="请输入题目"
          />
        </el-form-item>
        <el-form-item label="答案" prop="answer" height="96px">
          <el-input
            v-model="questionFormData.answer"
            type="textarea"
            :rows="6"
            placeholder="请输入答案"
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="state">
          <el-switch v-model="questionFormData.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="questionDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveQuestion">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import http from "@/http"; // 导入接口

// 类型定义
interface BankItem {
  id: string;
  title: string;
  categoryID: string;
  categoryName?: string;
  orderNum: number;
  state: number;
  creationTime: string;
}

interface CategoryItem {
  id: string;
  name: string;
}

interface BankFormData {
  id?: string;
  name: string;
  categoryId: string;
  state: number;
}
interface QuestionItem {
  id: string;
  bankID: string;
  topic: string;
  answer: string;
  state: number;
  publishTime: string;
}

interface QuestionFormData {
  id?: string;
  bankID: string;
  topic: string;
  answer: string;
  state: number;
}

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0,
});

// 计算当前页数据
const currentPageData = computed(() => {
  const startIndex = (pagination.currentPage - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  return bankList.value.slice(startIndex, endIndex);
});

// 状态管理
const loading = ref(false);
const questionLoading = ref(false);
const dialog = reactive({ title: "新增题库", visible: false });
const questionDialog = reactive({ title: "新增题目", visible: false });
const bankDetailDialog = reactive({ title: "", visible: false });

// 查询参数
const queryParams = reactive({
  bankKeywords: "",
  categoryId: "",
});

// 数据列表
const bankList = ref<BankItem[]>([]);
const categoryOptions = ref<CategoryItem[]>([]);
const questionList = ref<QuestionItem[]>([]);

// 表单数据
const formData = ref<BankFormData>({
  name: "",
  categoryId: "",
  state: 1,
});
const questionFormData = ref<QuestionFormData>({
  bankID: "",
  topic: "",
  answer: "",
  state: 1,
});

// 表单验证规则
const formRules = reactive({
  name: [{ required: true, message: "请输入题库名称", trigger: "blur" }],
  categoryId: [{ required: true, message: "请选择课程分类", trigger: "change" }],
});

const questionFormRules = reactive({
  bankID: [{ required: true, message: "请选择所属题库", trigger: "change" }],
  topic: [{ required: true, message: "请输入题目内容", trigger: "blur" }],
  answer: [{ required: true, message: "请输入答案", trigger: "blur" }],
});
const currentBankId = ref(""); // 当前查看的题库ID

// 引用
const queryFormRef = ref(null);
const menuFormRef = ref(null);
const questionFormRef = ref(null);

// 加载数据
async function loadData() {
  try {
    loading.value = true;
    // 获取分类列表
    const categoryRes = await http.getCategoryList();
    categoryRes.data = categoryRes;
    categoryOptions.value = categoryRes.data;

    // 获取题库列表
    const bankRes = await http.getBankList();
    bankRes.data = bankRes;
    bankList.value = bankRes.data;

    pagination.total = bankList.value.length;
  } catch (error) {
    ElMessage.error("数据加载失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
}

// 搜索功能
async function handleQuery() {
  loading.value = true;
  try {
    // 调用接口搜索题库
    const bankRes = await http.getBankList(queryParams.bankKeywords.trim(), queryParams.categoryId);
    bankRes.data = bankRes;
    bankList.value = bankRes.data;
    pagination.total = bankList.value.length;
    pagination.currentPage = 1;
  } catch (error) {
    ElMessage.error("搜索失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
}

// 查看题目列表
async function handleView(row: BankItem) {
  try {
    currentBankId.value = row.id;
    questionLoading.value = true;
    bankDetailDialog.title = row.title;
    bankDetailDialog.visible = true;

    // 获取当前题库的题目列表
    const questions = await http.getQuestionList(row.id);
    questions.data = questions;
    questionList.value = questions.data;
  } catch {
    ElMessage.error("获取题目列表失败");
  } finally {
    questionLoading.value = false;
  }
}

// 带当前题库ID的新增题目方法
function handleOpenQuestionDialogWithBank() {
  questionFormData.value = {
    bankID: currentBankId.value, // 自动关联当前查看的题库
    topic: "",
    answer: "",
    state: 0,
  };
  questionDialog.title = "新增题目";
  questionDialog.visible = true;
}

// 编辑题目
function handleEditQuestion(row: QuestionItem) {
  questionFormData.value = { ...row };
  questionDialog.title = "编辑题目";
  questionDialog.visible = true;
}

// 保存题目
async function handleSaveQuestion() {
  // @ts-ignore
  questionFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      questionLoading.value = true;
      try {
        if (questionFormData.value.id) {
          // 编辑题目
          await http.updateQuestion(
            questionFormData.value.id,
            questionFormData.value.bankID,
            questionFormData.value.topic,
            questionFormData.value.answer,
            questionFormData.value.state
          );
        } else {
          // 新增题目
          await http.createQuestion(
            questionFormData.value.bankID,
            questionFormData.value.topic,
            questionFormData.value.answer,
            questionFormData.value.state
          );
        }

        // 刷新题目列表和题库列表
        await reloadQuestionList(questionFormData.value.bankID);
        await reloadBankList();
        questionDialog.visible = false;
        ElMessage.success(`${questionFormData.value.id ? "编辑" : "新增"}题目成功`);
      } catch {
        ElMessage.error("操作失败");
      } finally {
        questionLoading.value = false;
      }
    }
  });
}

// 变更题目状态
async function handleQuestionStatusChange(row: QuestionItem) {
  const action = row.state === 1 ? "下架" : "上架";
  ElMessageBox.confirm(`确定要${action}题目【${row.topic}】吗？`, "提示")
    .then(async () => {
      questionLoading.value = true;
      try {
        await http.changeQuestionState(row.id);
        await reloadQuestionList(currentBankId.value);
        ElMessage.success(`${action}成功`);
      } catch {
        ElMessage.error(`${action}失败`);
      } finally {
        questionLoading.value = false;
      }
    })
    .catch(() => {
      ElMessage.info(`已取消${action}`);
    });
}

// 打开题库表单
function handleOpenDialog(id?: string) {
  if (id) {
    const item = bankList.value.find((item) => item.id === id);
    if (item) {
      formData.value = {
        id: item.id,
        name: item.title,
        categoryId: item.categoryID,
        state: item.state,
      };
      dialog.title = "编辑题库";
    }
  } else {
    resetForm();
    dialog.title = "新增题库";
  }
  dialog.visible = true;
}

// 重置题库表单
function resetForm() {
  formData.value = {
    name: "",
    categoryId: "",
    state: 0,
  };
  // @ts-ignore
  menuFormRef.value?.resetFields();
}

// 刷新题目列表
async function reloadQuestionList(bankId: string) {
  if (!bankId) return;
  const res = await http.getQuestionList(bankId);
  res.data = res;
  questionList.value = res.data;
}

// 刷新题库列表
async function reloadBankList() {
  const bankRes = await http.getBankList(queryParams.bankKeywords.trim(), queryParams.categoryId);
  bankRes.data = bankRes;
  bankList.value = bankRes.data;
  pagination.total = bankList.value.length;
}

// 保存题库
async function handleSave() {
  // @ts-ignore
  menuFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      try {
        const categoryName =
          categoryOptions.value.find((cat) => cat.id === formData.value.categoryId)?.name || "";

        if (formData.value.id) {
          // 编辑题库
          await http.updateBank(
            formData.value.id,
            formData.value.name,
            formData.value.categoryId,
            formData.value.state,
            categoryName
          );
        } else {
          // 新增题库
          await http.createBank(
            formData.value.name,
            formData.value.categoryId,
            formData.value.state,
            categoryName
          );
        }

        // 刷新题库列表
        await reloadBankList();
        dialog.visible = false;
        ElMessage.success(`${formData.value.id ? "编辑" : "新增"}题库成功`);
      } catch (error) {
        ElMessage.error("操作失败");
        console.error(error);
      } finally {
        loading.value = false;
      }
    }
  });
}

// 处理题库状态变更
async function handleStatusChange(row: BankItem) {
  const action = row.state === 1 ? "下架" : "上架";
  ElMessageBox.confirm(`确定要${action}题库【${row.title}】吗？`, "提示")
    .then(async () => {
      loading.value = true;
      try {
        // 调用接口更新状态
        await http.changeBankState(row.id);

        // 更新本地状态
        row.state = row.state === 1 ? 0 : 1;

        ElMessage.success(`${action}成功`);
      } catch (error) {
        ElMessage.error(`${action}失败`);
        console.error(error);
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      ElMessage.info(`已取消${action}`);
    });
}

// 每页条数变化
function handleSizeChange(size: number) {
  pagination.pageSize = size;
  pagination.currentPage = 1;
}

// 页码变化
function handleCurrentChange(page: number) {
  pagination.currentPage = page;
}

// 初始化
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
}

.input-group {
  display: flex;
  gap: 10px;
}

.pagination {
  float: right;
}
</style>
